package com.kfm.ding.service.impl;

import com.kfm.ding.service.ChatService;
import com.unfbx.chatgpt.OpenAiClient;
import com.unfbx.chatgpt.entity.chat.ChatCompletion;
import com.unfbx.chatgpt.entity.chat.ChatCompletionResponse;
import com.unfbx.chatgpt.entity.chat.Message;
import com.unfbx.chatgpt.interceptor.OpenAILogger;
import com.unfbx.chatgpt.interceptor.OpenAiResponseInterceptor;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.net.InetSocketAddress;
import java.net.Proxy;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class ChatServiceImpl implements ChatService {


    @Resource
    private RedisTemplate<String, List<Message>> redisTemplate;
    @Value("${ding.key}")
    private String key;
    @Value("${ding.host}")
    private String host;

    @Override
    public String ask(String question, String id) {
        // https://api.openai.com/v1/chat/complations
        // HttpRequest.post(https://ycdl.ysywy.shop/v1/chat/complations)
        // https://ycdl.ysywy.shop/v1/chat/complations ==> https://api.openai.com/
        // 国内访问需要做代理，国外服务器不需要
        HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor(new OpenAILogger());
        //！！！！千万别再生产或者测试环境打开BODY级别日志！！！！
        //！！！生产或者测试环境建议设置为这三种级别：NONE,BASIC,HEADERS,！！！
        httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.HEADERS);
        OkHttpClient okHttpClient = new OkHttpClient
                .Builder()
                .addInterceptor(httpLoggingInterceptor)// 自定义日志输出
                .addInterceptor(new OpenAiResponseInterceptor())// 自定义返回值拦截
                .connectTimeout(10, TimeUnit.SECONDS)// 自定义超时时间
                .writeTimeout(30, TimeUnit.SECONDS)// 自定义超时时间
                .readTimeout(30, TimeUnit.SECONDS)// 自定义超时时间
                .build();
        // 构建客户端
        OpenAiClient openAiClient = OpenAiClient.builder()
                .apiKey(Arrays.asList("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"))
                .okHttpClient(okHttpClient)
                // 自己做了代理就传代理地址，没有可不不传
                .apiHost("")
                .build();
        // 聊天模型：gpt-3.5
        Message message = Message.builder().role(Message.Role.USER).content(question).build();
        // 获取redis中存储的聊天记录
        List<Message> messages = redisTemplate.opsForValue().get(id);
        if (messages == null) {
            messages = new ArrayList<>();
        }
        // 如果存在 在发送给chatGPT的时候携带上
        messages.add(message);
        ChatCompletion chatCompletion = ChatCompletion.builder().messages(messages).build();
        ChatCompletionResponse chatCompletionResponse = openAiClient.chatCompletion(chatCompletion);
        log.info("chat响应{}", chatCompletionResponse);

        return chatCompletionResponse.getChoices().get(0).getMessage().getContent();
    }
}
